import { BaseModule, IModule } from './base/BaseModule';
import { GameFramework } from './base/GameFramework';
import { EventSystem } from './EventSystem';

export class NetworkSystem extends BaseModule {
   

    private _socket: WebSocket | null = null;
    private _msgHandlers: Map<number, Function> = new Map();
    private _isConnected: boolean = false;
    private _reconnectInterval: number = 5000; // 重连间隔毫秒
    private _reconnectTimer: any = null;
    private _maxReconnectAttempts: number = 5;
    private _reconnectAttempts: number = 0;
    private _url: string = "";

    init() {
        // 初始化网络系统
        console.log("NetworkSystem initialized");
    }
    shutdown(): void {
        console.log("NetworkSystem shutdown");
    }
    /**
     * 连接到服务器
     * @param url 服务器地址
     */n
    conect(url: string) {
        this._url = url;
        this._connect();
    }

    private _connect() {
        if (this._socket) {
            this._socket.close();
        }

        if (!this._url) {
            console.error("未设置服务器地址");
            return;
        }

        try {
            console.log(`正在连接到服务器: ${this._url}`);
            this._socket = new WebSocket(this._url);
            this._socket.binaryType = 'arraybuffer';
            
            this._socket.onopen = () => {
                this._isConnected = true;
                this._reconnectAttempts = 0;
                console.log("WebSocket连接成功");
                this._onConnectionOpen();
            };

            this._socket.onmessage = (e) => {
                this._onMessage(e.data);
            };

            this._socket.onclose = () => {
                this._isConnected = false;
                console.log("WebSocket连接关闭");
                this._onConnectionClose();
            };

            this._socket.onerror = (error) => {
                console.error("WebSocket连接错误:", error);
                this._onConnectionError(error);
            };
        } catch (error) {
            console.error("WebSocket连接失败:", error);
        }
    }

    private _onConnectionOpen() {
        // 连接建立时的处理
        GameFramework.event.emit("NETWORK_CONNECTED");
    }

    private _onConnectionClose() {
        // 连接关闭时的处理
        GameFramework.event.emit("NETWORK_DISCONNECTED");
        
        // 尝试重连
        if (this._reconnectAttempts < this._maxReconnectAttempts) {
            this._reconnectAttempts++;
            console.log(`尝试重连 (${this._reconnectAttempts}/${this._maxReconnectAttempts})`);
            this._reconnectTimer = setTimeout(() => {
                this._connect();
            }, this._reconnectInterval);
        }
    }

    private _onConnectionError(error: any) {
        // 连接错误时的处理
        GameFramework.event.emit("NETWORK_ERROR", error);
    }

    /**
     * 发送消息
     * @param cmd 命令ID
     * @param data 数据
     */
    send(cmd: number, data: Uint8Array) {
        if (!this._isConnected || !this._socket) {
            console.warn("WebSocket未连接，无法发送消息");
            return;
        }

        try {
            const header = new Uint8Array(4);
            new DataView(header.buffer).setUint32(0, cmd, false);
            const packet = new Uint8Array([...header, ...data]);
            this._socket.send(packet);
        } catch (error) {
            console.error("发送消息失败:", error);
        }
    }

    /**
     * 注册消息处理器
     * @param cmd 命令ID
     * @param handler 处理函数
     */
    registerHandler(cmd: number, handler: Function) {
        this._msgHandlers.set(cmd, handler);
    }

    /**
     * 注销消息处理器
     * @param cmd 命令ID
     */
    unregisterHandler(cmd: number) {
        this._msgHandlers.delete(cmd);
    }

    private _onMessage(buffer: ArrayBuffer) {
        try {
            if (buffer.byteLength < 4) {
                console.warn("收到无效消息，长度不足");
                return;
            }
            
            const dataView = new DataView(buffer);
            const cmd = dataView.getUint32(0, false);
            const handler = this._msgHandlers.get(cmd);
            
            if (handler) {
                handler(buffer.slice(4));
            } else {
                console.warn(`未找到命令 ${cmd} 的处理器`);
            }
        } catch (error) {
            console.error("消息解析失败:", error);
        }
    }

    /**
     * 检查是否已连接
     * @returns boolean
     */
    isConnected(): boolean {
        return this._isConnected;
    }

    /**
     * 断开连接
     */
    disconnect() {
        if (this._reconnectTimer) {
            clearTimeout(this._reconnectTimer);
            this._reconnectTimer = null;
        }
        
        if (this._socket) {
            this._socket.close();
            this._socket = null;
        }
        
        this._isConnected = false;
    }
}